import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';

interface CompletionData {
    [trigger: string]: string[]; // 键是触发前缀，值是补全项数组
}

function loadCompletionsData(context: vscode.ExtensionContext) {
    try {
        const filePath = path.join(context.extensionPath, 'data', 'code_completer.json');
        if (!fs.existsSync(filePath)) {
            throw new Error(`Completions file not found at: ${filePath}`);
        }
        const data = JSON.parse(fs.readFileSync(filePath, 'utf8')) as CompletionData;
        return data;
    }catch (error){
        console.error('Error loading comleter data:', error)
        return {};
    }
}

export function activate(context: vscode.ExtensionContext) {
    console.log('Plugin activated!'); // 插件激活日志
    // 读取json文件
    const completionsData = loadCompletionsData(context)

    // 定义补全提供器
    const provider: vscode.CompletionItemProvider = {
        provideCompletionItems(document, position) {
            // 获取当前行的文本
            const line = document.lineAt(position.line).text;
            // 获取光标前的文本（—即用户输入的前缀）
            const prefix = line.slice(0, position.character);
            // 遍历所有触发前缀，找到匹配的
        for (const [trigger, items] of Object.entries(completionsData)) {
            if (prefix.endsWith(trigger)) { // 直接匹配触发前缀（如 "prop." 或 "geom."）
                return items.map(label => {
                    const completion = new vscode.CompletionItem(label);
                    return completion;
                });
            }
        }
            
            return [];
        }
    };

    vscode.languages.registerCompletionItemProvider(
        ['python'],
        provider,
        '.'
    );
}

export function deactivate() {}